package com.share.rabbitmq.topic;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.share.rabbitmq.RabbitMQConnection;

import java.util.HashMap;
import java.util.Map;

/**
 * @desc:topic交换机生产者
 * @author:caifan
 * @date:2020/3/1
 */
public class TopicExchangeProducer {
    public static void main(String[] args) throws Exception {
        Connection connect = RabbitMQConnection.connect();
//        simpleTopic(connect);
        dlxTopicExchange(connect);
    }

    /**
     * 死信exchange
     * @param connect
     * @throws Exception
     */
    public static void dlxTopicExchange(Connection connect) throws Exception {
        Channel channel = connect.createChannel();

        String exchangeName = "my.topicExchange";
        String queueName = "my.queue";
        String routing_key1 = "my.topic.abc";

        String dlxExchangeName = "my.dlx.topicExchange";
        String dlxQueueName = "my.dlx.queue";
        String dlxRouting_key1 = "my.dlx.topic.abc";

        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false, null);
        Map<String, Object> argMap = new HashMap<>();
        argMap.put("x-dead-letter-exchange", dlxExchangeName);
        channel.queueDeclare(queueName, true, false, false, argMap);
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                .contentType("application/json")
                .expiration("10000")
                .deliveryMode(2).build();
        String message = "{\"type\":\"topic\"}";
        channel.basicPublish(exchangeName, routing_key1, true, basicProperties, message.getBytes());
    }

    /**
     * 简单的发送消息
     * @param connect
     * @throws Exception
     */
    public static void simpleTopic(Connection connect) throws Exception {
        Channel channel = connect.createChannel();

        String exchangeName = "my.topicExchange";

        String routing_key1 = "my.topic.abc";
        String routing_key2 = "my.topic1";
        String routing_key3 = "my.topic2";

        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,true,null);

        channel.basicPublish(exchangeName, routing_key1, null, "第一条消息".getBytes());
        channel.basicPublish(exchangeName, routing_key2, null, "第二条消息".getBytes());
        channel.basicPublish(exchangeName, routing_key3, null, "第三条消息".getBytes());
    }
}
